<template>
  <div class="page-container">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back-btn" @click="goBack">
        <Left />
      </div>
      <div class="header-actions">
        <Find class="action-icon" @click="goToSearch" />
        <Heart class="action-icon" @click="toggleFavorite" />
      </div>
    </div>

    <!-- 商品图片轮播 -->
    <div class="product-images">
      <nut-swiper 
        :init-page="0" 
        :pagination-visible="true" 
        :pagination-color="'#426543'"
        :auto-play="false"
      >
        <nut-swiper-item v-for="(image, index) in product.images" :key="index">
          <img :src="image" :alt="product.name" class="product-image" />
        </nut-swiper-item>
      </nut-swiper>
    </div>

    <!-- 商品信息 -->
    <div class="product-info">
      <div class="product-price">
        <span class="current-price">¥{{ product.price }}</span>
        <span class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</span>
        <span class="discount" v-if="product.originalPrice">
          {{ Math.round((1 - product.price / product.originalPrice) * 100) }}%OFF
        </span>
      </div>
      
      <h1 class="product-name">{{ product.name }}</h1>
      
      <div class="product-tags" v-if="product.tags && product.tags.length">
        <span class="tag" v-for="tag in product.tags" :key="tag">{{ tag }}</span>
      </div>
      
      <div class="product-desc">{{ product.description }}</div>
      
      <div class="product-meta">
        <div class="meta-item">
          <span class="label">销量:</span>
          <span class="value">{{ product.sales }}件</span>
        </div>
        <div class="meta-item">
          <span class="label">评价:</span>
          <span class="value">{{ product.rating }}分</span>
        </div>
        <div class="meta-item">
          <span class="label">库存:</span>
          <span class="value">{{ product.stock }}件</span>
        </div>
      </div>
    </div>

    <!-- 规格选择 -->
    <div class="product-specs">
      <div class="spec-item" @click="showSpecSelector">
        <span class="spec-label">规格</span>
        <span class="spec-value">{{ selectedSpec || '请选择规格' }}</span>
        <Right class="arrow" />
      </div>
      
      <div class="spec-item" @click="showQuantitySelector">
        <span class="spec-label">数量</span>
        <span class="spec-value">{{ quantity }}件</span>
        <Right class="arrow" />
      </div>
    </div>

    <!-- 商品详情 -->
    <div class="product-detail">
      <div class="detail-tabs">
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'detail' }"
          @click="activeTab = 'detail'"
        >
          商品详情
        </div>
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'params' }"
          @click="activeTab = 'params'"
        >
          规格参数
        </div>
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'reviews' }"
          @click="activeTab = 'reviews'"
        >
          用户评价
        </div>
      </div>
      
      <div class="tab-content">
        <div v-if="activeTab === 'detail'" class="detail-content">
          <div class="detail-images">
            <img 
              v-for="(image, index) in product.detailImages" 
              :key="index"
              :src="image" 
              :alt="`${product.name}详情图${index + 1}`"
              class="detail-image"
            />
          </div>
        </div>
        
        <div v-if="activeTab === 'params'" class="params-content">
          <div class="param-list">
            <div 
              class="param-item" 
              v-for="param in product.params" 
              :key="param.key"
            >
              <span class="param-key">{{ param.key }}</span>
              <span class="param-value">{{ param.value }}</span>
            </div>
          </div>
        </div>
        
        <div v-if="activeTab === 'reviews'" class="reviews-content">
          <div class="review-list">
            <div 
              class="review-item" 
              v-for="review in product.reviews" 
              :key="review.id"
            >
              <div class="review-header">
                <img :src="review.avatar" :alt="review.username" class="review-avatar" />
                <div class="review-info">
                  <span class="review-username">{{ review.username }}</span>
                  <div class="review-rating">
                    <Fabulous 
                      v-for="i in 5" 
                      :key="i"
                      :class="{ active: i <= review.rating }"
                    />
                  </div>
                </div>
                <span class="review-time">{{ review.time }}</span>
              </div>
              <div class="review-content">{{ review.content }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-actions">
      <div class="action-left">
        <div class="action-btn" @click="goToCart">
          <Cart class="action-icon" />
          <span>购物车</span>
          <span class="cart-count" v-if="cartStore.totalCount">{{ cartStore.totalCount }}</span>
        </div>
        <div class="action-btn" @click="goToHome">
          <Home class="action-icon" />
          <span>首页</span>
        </div>
      </div>
      
      <div class="action-right">
        <nut-button 
          type="primary" 
          size="large"
          @click="addToCart"
          class="add-cart-btn"
        >
          加入购物车
        </nut-button>
        <nut-button 
          type="danger" 
          size="large"
          @click="buyNow"
          class="buy-now-btn"
        >
          立即购买
        </nut-button>
      </div>
    </div>

    <!-- 规格选择弹窗 -->
    <nut-popup v-model:visible="showSpecs" position="bottom" :style="{ height: '60%' }">
      <div class="spec-popup">
        <div class="popup-header">
          <h3>选择规格</h3>
          <span class="close-btn" @click="showSpecs = false">×</span>
        </div>
        <div class="spec-options">
          <div 
            class="spec-option" 
            v-for="spec in product.specs" 
            :key="spec.value"
            :class="{ active: selectedSpec === spec.value }"
            @click="selectSpec(spec.value)"
          >
            {{ spec.label }}
          </div>
        </div>
      </div>
    </nut-popup>

    <!-- 数量选择弹窗 -->
    <nut-popup v-model:visible="showQuantity" position="bottom" :style="{ height: '40%' }">
      <div class="quantity-popup">
        <div class="popup-header">
          <h3>选择数量</h3>
          <span class="close-btn" @click="showQuantity = false">×</span>
        </div>
        <div class="quantity-selector">
          <nut-button @click="decreaseQuantity" :disabled="quantity <= 1">
            <Minus />
          </nut-button>
          <span class="quantity-display">{{ quantity }}</span>
          <nut-button @click="increaseQuantity" :disabled="quantity >= product.stock">
            <Plus />
          </nut-button>
        </div>
      </div>
    </nut-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { useFavoritesStore } from '@/stores/favorites'
import { 
  Left, 
  Find, 
  Heart, 
  Right, 
  Cart, 
  Home, 
  Fabulous, 
  Plus, 
  Minus 
} from '@nutui/icons-vue'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
const favoritesStore = useFavoritesStore()

// 商品数据
const product = reactive({
  id: 1,
  name: 'iPhone 15 Pro Max 256GB 深空黑色',
  price: 9999,
  originalPrice: 10999,
  description: '搭载A17 Pro芯片，采用3nm工艺制程，性能提升20%，GPU性能提升20%。配备6.7英寸Super Retina XDR显示屏，支持ProMotion自适应刷新率技术。',
  images: [
    'https://picsum.photos/200/200?random=2',
    'https://picsum.photos/200/200?random=3',
    'https://picsum.photos/200/200?random=2'
  ],
  detailImages: [
    'https://picsum.photos/375/200?random=1',
    'https://picsum.photos/375/200?random=1',
    'https://picsum.photos/375/200?random=1'
  ],
  tags: ['热销', '新品', '限时优惠'],
  sales: 12580,
  rating: 4.8,
  stock: 999,
  specs: [
    { label: '深空黑色 256GB', value: '深空黑色 256GB' },
    { label: '深空黑色 512GB', value: '深空黑色 512GB' },
    { label: '深空黑色 1TB', value: '深空黑色 1TB' }
  ],
  params: [
    { key: '处理器', value: 'A17 Pro芯片' },
    { key: '存储', value: '256GB' },
    { key: '屏幕', value: '6.7英寸Super Retina XDR' },
    { key: '摄像头', value: '4800万像素主摄' },
    { key: '电池', value: '4441mAh' }
  ],
  reviews: [
    {
      id: 1,
      username: '用户001',
      avatar: 'https://picsum.photos/40/40?random=1',
      rating: 5,
      content: '手机很好用，性能强劲，拍照效果很棒！',
      time: '2024-01-15'
    },
    {
      id: 2,
      username: '用户002',
      avatar: 'https://picsum.photos/40/40?random=1',
      rating: 4,
      content: '整体不错，就是价格有点贵，希望能降价。',
      time: '2024-01-14'
    }
  ]
})

// 状态管理
const activeTab = ref('detail')
const selectedSpec = ref('')
const quantity = ref(1)
const showSpecs = ref(false)
const showQuantity = ref(false)

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 跳转到搜索页
const goToSearch = () => {
  router.push('/search')
}

// 跳转到购物车
const goToCart = () => {
  router.push('/cart')
}

// 跳转到首页
const goToHome = () => {
  router.push('/')
}

// 切换收藏
const toggleFavorite = () => {
  showToast('收藏功能开发中')
}

// 显示规格选择器
const showSpecSelector = () => {
  showSpecs.value = true
}

// 显示数量选择器
const showQuantitySelector = () => {
  showQuantity.value = true
}

// 选择规格
const selectSpec = (spec) => {
  selectedSpec.value = spec
  showSpecs.value = false
}

// 增加数量
const increaseQuantity = () => {
  if (quantity.value < product.stock) {
    quantity.value++
  }
}

// 减少数量
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

// 添加到购物车
const addToCart = () => {
  if (!selectedSpec.value) {
    showToast('请选择商品规格')
    return
  }
  
  const productToAdd = {
    ...product,
    selectedSpec: selectedSpec.value,
    quantity: quantity.value
  }
  
  cartStore.addToCart(productToAdd)
  showToast('已添加到购物车')
}

// 立即购买
const buyNow = () => {
  if (!selectedSpec.value) {
    showToast('请选择商品规格')
    return
  }
  
  // 添加到购物车并跳转到结算页
  addToCart()
  setTimeout(() => {
    router.push('/checkout')
  }, 1000)
}

// 显示提示
const showToast = async (message) => {
  // 使用NutUI的Toast组件
  try {
    // 动态导入NutUI的showToast方法
    const { showToast } = await import('@nutui/nutui')
    showToast({
      content: message,
      type: 'success',
      duration: 2000
    })
  } catch (error) {
    // 如果失败，使用备选方案
    console.log('Toast提示:', message)
    createSimpleToast(message)
  }
}

// 创建简单的Toast提示
const createSimpleToast = (message) => {
  const toast = document.createElement('div')
  toast.style.cssText = `
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 12px 20px;
    border-radius: 6px;
    font-size: 14px;
    z-index: 9999;
    pointer-events: none;
    max-width: 80%;
    text-align: center;
  `
  toast.textContent = message
  document.body.appendChild(toast)
  
  setTimeout(() => {
    if (document.body.contains(toast)) {
      document.body.removeChild(toast)
    }
  }, 2000)
}

onMounted(() => {
  // 从路由参数获取商品ID
  const productId = route.params.id
  console.log('商品ID:', productId)
  
  // 这里可以根据商品ID加载商品数据
  // loadProduct(productId)
})
</script>

<style scoped>
.header {
  background: white;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
  border-bottom: 1px solid #f0f0f0;
}

.back-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
}

.header-actions {
  display: flex;
  gap: 16px;
}

.action-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
  color: #666;
}

.product-images {
  margin-bottom: 16px;
}

.product-image {
  width: 100%;
  height: 375px;
  object-fit: cover;
}

.product-info {
  background: white;
  padding: 20px 16px;
  margin-bottom: 12px;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.current-price {
  font-size: 24px;
  font-weight: 600;
  color: #ff4757;
}

.original-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
}

.discount {
  background: #ff4757;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.product-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
  line-height: 1.4;
}

.product-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.tag {
  background: #f0f0f0;
  color: #666;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.product-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 16px;
}

.product-meta {
  display: flex;
  gap: 24px;
}

.meta-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.label {
  font-size: 12px;
  color: #999;
}

.value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.product-specs {
  background: white;
  margin-bottom: 12px;
}

.spec-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.spec-item:last-child {
  border-bottom: none;
}

.spec-label {
  font-size: 14px;
  color: #333;
}

.spec-value {
  font-size: 14px;
  color: #666;
  flex: 1;
  text-align: right;
  margin-right: 8px;
}

.arrow {
  color: #ccc;
  font-size: 16px;
}

.product-detail {
  background: white;
  margin-bottom: 80px;
}

.detail-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 16px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

.tab-item.active {
  color: #ff4757;
  border-bottom-color: #ff4757;
}

.tab-content {
  padding: 20px 16px;
}

.detail-images {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-image {
  width: 100%;
  height: auto;
}

.param-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.param-item {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.param-item:last-child {
  border-bottom: none;
}

.param-key {
  font-size: 14px;
  color: #666;
}

.param-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.review-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.review-item {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20px;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.review-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.review-info {
  flex: 1;
}

.review-username {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  display: block;
  margin-bottom: 4px;
}

.review-rating {
  display: flex;
  gap: 2px;
}

.review-rating .nut-icon {
  color: #ddd;
  font-size: 14px;
}

.review-rating .nut-icon.active {
  color: #ffd700;
}

.review-time {
  font-size: 12px;
  color: #999;
}

.review-content {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 12px 16px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.action-left {
  display: flex;
  gap: 24px;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  position: relative;
}

.action-btn .action-icon {
  width: 20px;
  height: 20px;
  color: #666;
}

.action-btn span {
  font-size: 10px;
  color: #666;
}

.cart-count {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #ff4757;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 16px;
  text-align: center;
}

.action-right {
  display: flex;
  gap: 12px;
}

.add-cart-btn, .buy-now-btn {
  height: 40px;
  font-size: 14px;
}

.spec-popup, .quantity-popup {
  padding: 20px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.popup-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.close-btn {
  font-size: 24px;
  color: #999;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.spec-option {
  padding: 12px 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  transition: all 0.3s;
}

.spec-option:hover {
  border-color: #ff4757;
}

.spec-option.active {
  border-color: #ff4757;
  background: #ff4757;
  color: white;
}

.quantity-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
}

.quantity-display {
  font-size: 18px;
  color: #333;
  min-width: 60px;
  text-align: center;
}
</style>
